import React, { useState } from 'react';
import { 
  Modal, 
  Card, 
  Button, 
  Space, 
  Row, 
  Col, 
  InputNumber, 
  Switch, 
  Divider,
  Alert,
  Tag,
  Tooltip,
  message
} from 'antd';
import { 
  PlayCircleOutlined,
  PauseCircleOutlined,
  StopOutlined,
  ToolOutlined,
  WarningOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined
} from '@ant-design/icons';

interface ElevatorControlPanelProps {
  visible: boolean;
  onClose: () => void;
  elevator: {
    id: string;
    name: string;
    status: 'running' | 'idle' | 'maintenance' | 'fault';
    direction: 'up' | 'down' | 'idle';
    currentFloor: number;
    targetFloor?: number;
    load: number;
    maxLoad: number;
    minFloor: number;
    maxFloor: number;
    emergencyStop: boolean;
    maintenanceMode: boolean;
  };
  onControl: (action: string, params?: any) => void;
}

const ElevatorControlPanel: React.FC<ElevatorControlPanelProps> = ({ 
  visible, 
  onClose, 
  elevator, 
  onControl 
}) => {
  const [targetFloor, setTargetFloor] = useState<number>(elevator.currentFloor);
  const [loading, setLoading] = useState(false);

  // 处理楼层控制
  const handleFloorControl = async (floor: number) => {
    if (elevator.status === 'fault') {
      message.error('电梯故障，无法操作');
      return;
    }
    
    if (elevator.maintenanceMode) {
      message.warning('电梯处于维护模式');
      return;
    }

    setLoading(true);
    try {
      await onControl('goto_floor', { floor });
      message.success(`电梯正在前往 ${floor} 楼`);
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理紧急停止
  const handleEmergencyStop = async () => {
    setLoading(true);
    try {
      await onControl('emergency_stop');
      message.warning('紧急停止已激活');
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理维护模式切换
  const handleMaintenanceToggle = async (enabled: boolean) => {
    setLoading(true);
    try {
      await onControl('maintenance_mode', { enabled });
      message.success(enabled ? '已进入维护模式' : '已退出维护模式');
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理电梯启停
  const handleStartStop = async (action: 'start' | 'stop') => {
    setLoading(true);
    try {
      await onControl(action);
      message.success(action === 'start' ? '电梯已启动' : '电梯已停止');
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 生成楼层按钮
  const renderFloorButtons = () => {
    const floors = [];
    for (let i = elevator.maxFloor; i >= elevator.minFloor; i--) {
      floors.push(
        <Col span={6} key={i}>
          <Button
            type={i === elevator.currentFloor ? 'primary' : 'default'}
            size="large"
            block
            disabled={elevator.status === 'fault' || elevator.maintenanceMode || loading}
            onClick={() => handleFloorControl(i)}
            style={{ 
              height: '50px',
              fontSize: '16px',
              fontWeight: 'bold'
            }}
          >
            {i}F
          </Button>
        </Col>
      );
    }
    return floors;
  };

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <span>{elevator.name} - 控制面板</span>
          <Tag color={elevator.status === 'fault' ? 'red' : 'blue'} style={{ marginLeft: 8 }}>
            {elevator.status === 'running' ? '运行中' :
             elevator.status === 'idle' ? '空闲' :
             elevator.status === 'maintenance' ? '维护中' : '故障'}
          </Tag>
        </div>
      }
      open={visible}
      onCancel={onClose}
      footer={null}
      width={600}
      destroyOnHidden
    >
      {/* 状态警告 */}
      {elevator.status === 'fault' && (
        <Alert
          message="电梯故障"
          description="电梯检测到故障，请联系维护人员处理"
          type="error"
          icon={<WarningOutlined />}
          style={{ marginBottom: 16 }}
        />
      )}

      {elevator.emergencyStop && (
        <Alert
          message="紧急停止激活"
          description="电梯已紧急停止，请检查安全状况后重新启动"
          type="warning"
          style={{ marginBottom: 16 }}
        />
      )}

      {/* 当前状态 */}
      <Card title="当前状态" size="small" style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={8}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold' }}>
                {elevator.currentFloor}F
              </div>
              <div style={{ color: '#666' }}>当前楼层</div>
            </div>
          </Col>
          <Col span={8}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '18px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {elevator.direction === 'up' && <ArrowUpOutlined style={{ color: '#52c41a' }} />}
                {elevator.direction === 'down' && <ArrowDownOutlined style={{ color: '#1890ff' }} />}
                <span style={{ marginLeft: 4 }}>
                  {elevator.direction === 'idle' ? '停止' : 
                   elevator.direction === 'up' ? '上行' : '下行'}
                </span>
              </div>
              <div style={{ color: '#666' }}>运行方向</div>
            </div>
          </Col>
          <Col span={8}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '18px' }}>
                {elevator.load}kg / {elevator.maxLoad}kg
              </div>
              <div style={{ color: '#666' }}>负载</div>
            </div>
          </Col>
        </Row>
      </Card>

      {/* 楼层控制 */}
      <Card title="楼层控制" size="small" style={{ marginBottom: 16 }}>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <span>目标楼层:</span>
            <InputNumber
              min={elevator.minFloor}
              max={elevator.maxFloor}
              value={targetFloor}
              onChange={(value) => setTargetFloor(value || elevator.currentFloor)}
              disabled={elevator.status === 'fault' || elevator.maintenanceMode || loading}
            />
            <Button
              type="primary"
              onClick={() => handleFloorControl(targetFloor)}
              disabled={
                targetFloor === elevator.currentFloor || 
                elevator.status === 'fault' || 
                elevator.maintenanceMode || 
                loading
              }
              loading={loading}
            >
              前往
            </Button>
          </Space>
        </div>
        
        <Divider orientation="left" plain>快速选择楼层</Divider>
        <Row gutter={[8, 8]}>
          {renderFloorButtons()}
        </Row>
      </Card>

      {/* 控制操作 */}
      <Card title="控制操作" size="small">
        <Row gutter={16}>
          <Col span={12}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <span style={{ marginRight: 8 }}>维护模式:</span>
                <Switch
                  checked={elevator.maintenanceMode}
                  onChange={handleMaintenanceToggle}
                  disabled={elevator.status === 'fault' || loading}
                  loading={loading}
                />
              </div>
              
              <Space>
                <Tooltip title="启动电梯">
                  <Button
                    type="primary"
                    icon={<PlayCircleOutlined />}
                    onClick={() => handleStartStop('start')}
                    disabled={
                      elevator.status === 'running' || 
                      elevator.status === 'fault' || 
                      loading
                    }
                    loading={loading}
                  >
                    启动
                  </Button>
                </Tooltip>
                
                <Tooltip title="停止电梯">
                  <Button
                    icon={<PauseCircleOutlined />}
                    onClick={() => handleStartStop('stop')}
                    disabled={
                      elevator.status === 'idle' || 
                      elevator.status === 'fault' || 
                      loading
                    }
                    loading={loading}
                  >
                    停止
                  </Button>
                </Tooltip>
              </Space>
            </Space>
          </Col>
          
          <Col span={12}>
            <div style={{ textAlign: 'right' }}>
              <Button
                danger
                type="primary"
                icon={<StopOutlined />}
                size="large"
                onClick={handleEmergencyStop}
                disabled={elevator.emergencyStop || loading}
                loading={loading}
                style={{ width: '120px', height: '60px' }}
              >
                紧急停止
              </Button>
            </div>
          </Col>
        </Row>
      </Card>
    </Modal>
  );
};

export default ElevatorControlPanel;